import { parse } from 'qs';
import {queryHistory} from '../services/indexPage';
import moment from 'moment';
export default {
  namespace : 'historyData',
  state : {
    records : [],
    loading : false
  },
  subscriptions : {
    setup({ history, dispatch }){
      history.listen( ({ pathname, search }) => {
        if(!!search && pathname === "/history"){
          let opt = parse(search.substr(1))
          dispatch({ type : 'queryHistory', payload : opt })
        }else if(!search && pathname==="/history") {
          let begin = moment((Date.now() - 1000*60*60*24)).format("YYYYMMDD");
          let end = moment(Date.now()).format("YYYYMMDD")
          console.log(begin,end)
          dispatch({
            type : "queryHistory",
            payload : {
              datebegin : begin,
              dateend : end
            }
          })
        }
      })
    }
  },
  effects : {
    *queryHistory({ payload }, { call, put }){
      yield put({ type : "showLoading"})
      const { data : his } = yield call(queryHistory, payload)
      yield put({
        type : "queryHistorySuccess",
        payload : his
      })
      yield put({ type : "hideLoading"})
    }
  },
  reducers : {
    queryHistorySuccess(state, { payload }) {
      return {
        ...state,
        records : payload
      }
    },
    showLoading(state) {
      return {
        ...state,
        loading : true
      }
    },
    hideLoading(state) {
      return {
        ...state,
        loading : false
      }
    }
  }
}